import codecs
from md2html import *
import yaml
import os
from baseinfo import *
import shutil
import os
import random
import hashlib
tot=60#[0,tot-1]
daohangQwQ="""
	<nav class="navbar navbar-default header card" role="navigation" style="width: 100%;">
	<div class="container-fluid"> 
	<div class="navbar-header">
		<button type="button" class="navbar-toggle" data-toggle="collapse"
				data-target="#example-navbar-collapse">
			<span class="icon-bar"></span>
			<span class="icon-bar"></span>
			<span class="icon-bar"></span>
		</button>
		<a class="navbar-brand" href="/">"""+logo+"""</a>
	</div>
	<div class="collapse navbar-collapse" id="example-navbar-collapse">
		<ul class="nav navbar-nav" style="background-color:#fcfcfc">
			<li><a href="/"><i class="menu-item-icon fa fa-fw fa-home"></i>首页</a></li>
			<li><a href="/archives/"><i class="menu-item-icon fa fa-fw fa-archive"></i>文章</a></li>
			<li><a href="/tags/"><i class="menu-item-icon fa fa-fw fa-tags"></i>标签</a></li>
			<li><a href="/settings/"><i class="menu-item-icon fa fa-fw fa-cogs"></i>设置</a></li>
			<!--li><a href="/about/"><i class="menu-item-icon fa fa-fw fa-user"></i>关于</a></li-->
			<li><a href="/games/"><i class="menu-item-icon fa fa-fw fa-gamepad"></i>其它</a></li>
			

		</ul>
	</div>
	</div>
	</nav>"""
my="""
			<div class="panel panel-default card">
					<div class="panel-heading">
						<h3 class="panel-title">
							<i class="fa fa-user-circle-o"></i>&emsp;
							<strong>"""+name+"""</strong>
						</h3>
					</div>
					<div style="width: 60%;display: inline-block;padding-top: 10px;">
						<ul class="propertyLinks" style="list-style-type: none;">
							<li>
								<img style="vertical-align:middle;position:relative;top:-2px" src="/img/rating-16x16.png">
								Rating:&nbsp;
								<span style="font-weight:bold;color: """+color+' ">'+rating+"""</span>
							</li>
							<li>
								<img style="vertical-align:middle;position:relative;top:-2px" src="/img/star_blue_16.png">
								Contribution:&nbsp;
								<span style="color:gray;font-weight:bold;">0</span>
							</li>
						</ul>
						<ul class="nav-links">
							<li><a href="/settings/">Settings</a></li>
							<li><a href="/archives/">Blog</a></li>
							<li><a href="/teams">Teams</a></li>
							<li><a href="/submissions/dingdingsb">Submissions</a></li>
							<li><a href="/usertalk">Talks</a></li>
							<li><a href="/contests/with/dingdingsb">Contests</a></li>
						</ul>
					</div>
					<div style="display:inline-block;vertical-align: top;margin: 10px;text-align: center;">
						<div style="height:50px;width:50px"><img src="/img/avatar.png"/></div>
						<div><a href="https://www.luogu.com.cn/user/174304" style="font-weight:bold;color:"""+color+'">'+name+"""</a></div>
					</div>
				</div>
		<div class="panel panel-default card">
				<div class="panel-heading">
					<h3 class="panel-title">
						<i class="fa fa-external-link"></i>&emsp;
						<strong>画中画</strong>
					</h3>
				</div>
				<div style="width:100%;margin:10px">
				<input type="text" id="url"/>
				<input value="创建" type="button" onclick="creat('kk')" /> 
				</div>
		</div>
		<script src="/js/hitokoto.js"></script>
							
"""
friend="""
	<div class="panel panel-default card">
				<div class="panel-heading">
					<h3 class="panel-title">
						<i class="fa fa-address-book"></i>&emsp;
						<strong>Top ratings</strong>
					</h3>
				</div>
				<table class="table table-striped">
					<th style="width: 20%;">#</th>
					<th style="width: 50%;">用户</th>
					<th style="width: 30%;">Rating</th>
					<tr>
						<td>1</td>
						<td><a class="lgm" href="https://www.luogu.com.cn/user/151935">Rainbow_sjy</span></td>
						<td>4000</td>
					</tr>
					<tr>
						<td>2</td>
						<td><a class="lgm" href="https://www.luogu.com.cn/user/220857">素质玩家孙1超</span></td>
						<td>3864</td>
					</tr>
					<tr>
						<td>3</td>
						<td><a class="lgm" href="https://www.luogu.com.cn/user/141179">pigstd</span></td>
						<td>3732</td>
					</tr>
					<tr>
						<td>4</td>
						<td><a class="lgm" href="https://www.luogu.com.cn/user/288460">xzggzh1</span></td>
						<td>3532</td>
					</tr>
				</table>
		</div>"""
header="""
	<head>
	<title>"""+title+"""</title>
	<meta charset="utf-8"/>
	<link rel="stylesheet" href="/font-awesome-4.7.0/css/font-awesome.min.css">

	<link rel="stylesheet" href="/bootstrap-3.3.7/css/bootstrap.min.css">
	<script src="/jquery-2.1.1/jquery.min.js"></script>
	<script src="/bootstrap-3.3.7/js/bootstrap.min.js"></script>

	<link rel="stylesheet" href="/css/bootstrap-slider.min.css">
	<script src="/js/bootstrap-slider.min.js"></script>
	
	<link rel="stylesheet" href="/css/main.css">
	<script src="/js/main.js"></script>
	
	<link rel="stylesheet" href="/css/cursor.css">
	<script src="/js/cursor.js"></script>
	
	
	<link rel="stylesheet" href="/css/code.css">
	<!--link rel="stylesheet" href="/css/markdown.css"-->
	
	<link rel="stylesheet" href="/css/head.css">

	<script src="/js/window.js"></script>
	<script src='//unpkg.com/valine/dist/Valine.min.js'></script>
	</head>"""
more="""
	<link rel="stylesheet" href="/katex/katex.min.css" crossorigin="anonymous">
	<script src="/katex/katex.min.js" crossorigin="anonymous"></script>
	<script src="/katex/contrib/mathtex-script-type.min.js" defer></script>
	<script defer src="/katex/contrib/auto-render.min.js"crossorigin="anonymous"
	    onload="renderMathInElement(document.body);"></script>
	<script>document.addEventListener("DOMContentLoaded", function() {renderMathInElement(document.body,{"delimiters":[{left: "$", right: "$", display: false}]});});</script>"""
tagjs="""<script>
					window.onload=function(){
						$('.tag2').css("display","inline");
						$('.tag1').css("display","none");
						$("#ttt1").click(function(){
							console.log("1");
							$('.tag2').css("display","inline");
							$('.tag1').css("display","none");
						});
						
						$("#ttt2").click(function(){
							console.log("2");
							$('.tag1').css("display","inline");
							$('.tag2').css("display","none");
						});
					}
					</script>"""
taghead="""<div class="panel-heading">
                        <h3 class="panel-title"><i class="fa fa-tags"></i>&emsp;{}</h3>
                    </div>"""
def pre(href):
	return '<a style="float: left;" href="%s"><i class="fa fa-angle-double-left"></i></a>'%href
def nxt(href):
	return '<a style="float: right;" href="%s"><i class="fa fa-angle-double-right"></i></a>'%href
def row(name,val):
	return """<div style="margin-top: 8px;display: flex;"> 
    <span style="flex: 1 0 auto;margin-right: 6px;">"""+name+"""</span>
    <span>"""+val+"""</span>
	</div>"""
def article(content,pages,infos,tags,imggg,info2):
	return """
<!DOCTYPE html>
<html>
"""+header+"""
<body>
"""+more+daohangQwQ+"""
<div class="container">
	<div style="height: 60px;"></div>
	<div class="row" >
		<div class="col-md-8">
			<div class="panel panel-default card" style="padding: 10px;position: relative;">
                <img src='"""+imggg+"""' style="width:100%"/>
				<span style="position: absolute;left:15px;bottom:15px;width:90%;">"""+info2+"""</span>
			</div>
			<div class="panel panel-default card" style="padding: 10px;" id="main">
                """+content+"""
			</div>
			<div class="panel panel-default card" style="padding: 10px;height: 50px;font-size: 20px;">
				"""+pages+"""
			</div>
			<div class="panel panel-default card" style="padding: 10px;font-size: 20px;" id="vcomments">
				
			</div>
			<script>
				new Valine({
					el: '#vcomments',
					appId: 'PAlFUPg0pQVTFTEo8gCB4BCf-gzGzoHsz',
					appKey: 'U38ejnLUiizJ6vLyp6ql4hRq',
					path: window.location.pathname
				})
			</script>
		</div>
		<div class="col-md-3">
				<div class="panel panel-default card">
				<div class="panel-heading">
					<h3 class="panel-title">
						<i class="fa fa-info"></i>&emsp;
						<strong>文章信息</strong>
					</h3>
				</div>
                <div style="margin: 10px;">
                    """+infos+"""
                </div>
				</div>
				<div class="panel panel-default card">
				<div class="panel-heading">
					<h3 class="panel-title">
						<i class="fa fa-tag"></i>&emsp;
						<strong>标签</strong>
					</h3>
				</div>
				<div style="margin: 10px;">
					"""+tags+"""
				</div>
				</div>
				"""+my+"""
				
				<span id="kk"></span>
				<div  id="myScrollspy" class="card" style="width: 100%;"  data-spy="affix">
					<script src="/js/make_toc.js"></script>
				</div>
		</div>
	</div>
 </div>
</body>
</html>
"""
Ts=set()
Cs=set()
Ys=set()
Imgg=dict()
def maketag(color,name,href):
	return '<a href="'+href+'" class="tag"><span  style="background-color: '+color+';">'+name+'</span></a>'
def read(name):
	input_file = codecs.open(name, mode="r", encoding="utf8")
	return input_file.read()
def write(name,text):
	if os.path.exists(name):
		if read(name)==text:
			print('skip')
			return
	output_file = codecs.open(name, mode="w", encoding="utf8")
	output_file.write(text)
def work(name,Pre,Nxt):
	global Ts
	global Cs
	global Ys
	text=read(name)
	print(name)
	(info,__,text)=text.partition("---")
	datas=yaml.load(info,Loader=yaml.FullLoader)
	tags=maketag("rgb(52, 152, 219)",str(datas['date'].year),"/tags/"+str(datas['date'].year)+"/")
	Ys.add(str(datas['date'].year))
	if 'tags' in datas and datas['tags']!=None:
		for i in datas['tags']:
			tags=tags+'&nbsp;'+maketag('rgb(231, 76, 60)',i,"/tags/"+i+"/")
			Ts.add(i)
	if 'categories' in datas and datas['categories']!=None:
		for i in datas['categories']:
			tags=tags+'&nbsp;'+maketag('rgb(82, 196, 26)',i,"/tags/"+i+"/")
			Cs.add(i)
	pages=""
	if Pre!="":
		pages=pages+pre(Pre)
	if Nxt!="":
		pages=pages+nxt(Nxt)
	infos=""
	infos=infos+row('标题','<font style="font-weight: bold">'+datas['title']+'</font>')
	infos=infos+row('日期',str(datas['date']))
	info2=""
	info2=info2+'<font class="view-text" style="color:#fcfcfc;font-size:25px">'+datas['title']+'</font>'
	info2=info2+'<br>'+tags
	print(name,Imgg[name])
	return article(deal(text),pages,infos,tags,Imgg[name],info2)
def get(name):
	#print(name)
	text=read(name)
	(info,__,text)=text.partition("---")
	datas = yaml.load(info,Loader=yaml.FullLoader)
	Top=0
	if "top" in datas:
		Top=datas['top']
	tag1=[]
	tag2=[]
	if 'tags' in datas and datas['tags']!=None:
		for i in datas['tags']:
			tag1.append(i)
	if 'categories' in datas and datas['categories']!=None:
		for i in datas['categories']:
			tag2.append(i)
	Date=datas['date']
	title=name
	title=title.partition("\\")[2]
	title=title.partition(".")[0]
	realtitle=datas['title']
	m=hashlib.md5()
	m.update(name.encode('utf-8'))
	imgg='/img/bg/'+str(int(m.hexdigest(),16)%tot)+".png"
	if 'img' in datas:
		imgg=datas['img']
	Imgg[name]=imgg
	return (Top,Date,title,tag1,tag2,realtitle,imgg)
def menu(content,pages,add):
	return """
	<!DOCTYPE html>
	<html>
	"""+header+"""
	<body>
	"""+more+daohangQwQ+"""
	<div class="container">
		<div style="height: 60px;"></div>
		<div class="row" >
			<div class="col-md-8">

				<div class="panel panel-default card" id="main">
                    """+add+"""
	                """+content+"""
				</div>
				<div class="panel panel-default card" style="padding: 10px;height: 50px;font-size: 20px;">
					"""+pages+"""
				</div>
			</div>
			<div class="col-md-3">

					"""+my+ friend+"""
			</div>
		</div>
	 </div>
	</body>
	</html>
	"""
def work2(works,nowpage,totpages,path,add=""):
	content="""<table class="table">
	<tbody>
	<tr><th style="width: 50%;">标题</th><th style="width: 25%;">标签<small><button class='tag2 btn btn-danger btn-xs' id="ttt2" style="display:none">显示标签</button><button class="tag1 btn btn-success btn-xs" id="ttt1" style="display:none">显示分类</button></small></th><th>时间 </th></tr>\n"""
	for i in range(0,len(works)):
		article=works[i]
		tag1=""
		tag2=""
		tag2=maketag("rgb(52, 152, 219)",str(article[1].year),"/tags/"+str(article[1].year)+"/")
		for A in article[3]:
			tag1=tag1+maketag('rgb(231, 76, 60)',A,"/tags/"+A+"/")
		for A in article[4]:
			tag2=tag2+maketag('rgb(82, 196, 26)',A,"/tags/"+A+"/")
		more='data-container="body" data-toggle="popover" data-placement="bottom" data-html="true"\
			data-content="<img src=\''+article[6]+'\'></img>" data-trigger="hover"'
		if i>prepage//2:
			more=more.replace("bottom","top")
		content=content+"<tr><td><a href='/article/"+article[2]+".html' "+more+">"+article[5]+"</a></td><td><span class='tag1' style='display:none'>"+tag1+"</span><span class='tag2' style='display:none'>"+tag2+"</span></td><td>"+str(article[1])+"</td></tr>\n"
	
	content=content+"</tbody></table>"
	pages=""
	if nowpage!=1:
		pages=pages+'<li><a href="'+path+str(nowpage-1)+'.html"><i class="fa fa-angle-left"></i></a></li>'
	for i in range(max(1,nowpage-3),min(totpages,nowpage+3)+1):
		if i != nowpage:
			pages=pages+'<li><a href="'+path+str(i)+'.html">'+str(i)+'</a></li>'
		else:
			pages=pages+'<li class="active"><a href="'+path+str(i)+'.html">'+str(i)+'</a></li>'
	if nowpage!=totpages:
		pages=pages+'<li><a href="'+path+str(nowpage+1)+'.html"><i class="fa fa-angle-right"></i></a></li>'
	
	pages='<ul class="pagination pagination-sm" style="margin: 0!important">'+pages+'</ul>'
	return menu(tagjs+content,pages,add)
def taglist(content):
	return """
	<!DOCTYPE html>
	<html>
	"""+header+"""
	<body>
	"""+more+daohangQwQ+"""
	<div class="container">
		<div style="height: 60px;"></div>
		<div class="row" >
			<div class="col-md-8">

				<div class="panel panel-default card" id="main">
                    """+taghead.format("<strong>标签列表</strong>")+"""
	                <div style="width:100%;padding:10px;">"""+content+"""</div>
				</div>
			</div>
			<div class="col-md-3">

					"""+my+ friend+"""
			</div>
		</div>
	 </div>
	</body>
	</html>
	"""
def workTag(arr):
    kkk=""
    tt=dict()
    for name in Ts:
        tt[name]=[]
        kkk=kkk+"&nbsp;"+maketag('rgb(231, 76, 60)',name,"/tags/"+name+"/")
    for i in range(0,len(arr)):
        for T in arr[i][3]:
            tt[T].append(arr[i])
    for name in Ts:
        if not os.path.exists("tags\\"+name+"\\"):
            os.mkdir("tags\\"+name)
        result=[tt[name][i:i+prepage] for i in range(0,len(tt[name]),prepage)]
        for i in range(0,len(result)):
            write("tags\\"+name+"\\"+str(i+1)+".html",
                work2(result[i],i+1,len(result),"/tags/"+name+"/",taghead.format(maketag('rgb(231, 76, 60)',name,"/tags/"+name+"/")))
                .replace('<li><a href="/tags/">','<li class="active"><a href="/tags/">'))
        shutil.copyfile("tags\\"+name+"\\1.html", "tags\\"+name+"\\index.html")

    tt=dict()
    for name in Cs:
        tt[name]=[]
        kkk=kkk+"&nbsp;"+maketag('rgb(82, 196, 26)',name,"/tags/"+name+"/")
    for i in range(0,len(arr)):
        for T in arr[i][4]:
            tt[T].append(arr[i])
    for name in Cs:
        if not os.path.exists("tags\\"+name+"\\"):
            os.mkdir("tags\\"+name)
        result=[tt[name][i:i+prepage] for i in range(0,len(tt[name]),prepage)]
        for i in range(0,len(result)):
            write("tags\\"+name+"\\"+str(i+1)+".html",
                work2(result[i],i+1,len(result),"/tags/"+name+"/",taghead.format(maketag('rgb(82, 196, 26)',name,"/tags/"+name+"/")))
                .replace('<li><a href="/tags/">','<li class="active"><a href="/tags/">'))
        shutil.copyfile("tags\\"+name+"\\1.html", "tags\\"+name+"\\index.html")


    tt=dict()
    for name in Ys:
        tt[name]=[]
        kkk=kkk+"&nbsp;"+maketag("rgb(52, 152, 219)",name,"/tags/"+name+"/")
    for i in range(0,len(arr)):
        tt[str(arr[i][1].year)].append(arr[i])
    for name in Ys:
        if not os.path.exists("tags\\"+name+"\\"):
            os.mkdir("tags\\"+name)
        result=[tt[name][i:i+prepage] for i in range(0,len(tt[name]),prepage)]
        for i in range(0,len(result)):
            write("tags\\"+name+"\\"+str(i+1)+".html",
                work2(result[i],i+1,len(result),"/tags/"+name+"/",taghead.format(maketag("rgb(52, 152, 219)",name,"/tags/"+name+"/")))
                .replace('<li><a href="/tags/">','<li class="active"><a href="/tags/">'))
        shutil.copyfile("tags\\"+name+"\\1.html", "tags\\"+name+"\\index.html")
    write("tags\\index.html",taglist(kkk).replace('<li><a href="/tags/">','<li class="active"><a href="/tags/">'))
def index(content):
	return """
	<!DOCTYPE html>
	<html>
	"""+header+"""
	<body>
	"""+more+daohangQwQ+"""
	<div class="container">
		<div style="height: 60px;"></div>
		<div class="row" >
			<div class="col-md-8">
	<div class="panel panel-default card">
				<div class="panel-heading">
					<h3 class="panel-title"><i class="fa fa-bullhorn"></i>&emsp;<strong>公告</strong></h3>
				</div>
				<table class="table">
					<th style="width: 80%;">标题</th><th>时间 </th>
					<tr><td><a href="/article/new-blog.html">新博客食用说明</a></td><td>2021-03-07 18:31:03</td></tr>
				</table>
			</div>
			<div class="panel panel-default card">
				<div class="panel-heading">
					<h3 class="panel-title"><i class="fa fa-archive"></i>&emsp;<strong>最新文章</strong></h3>
				</div>
				<table class="table">
					<th style="width: 80%;">标题</th><th>时间 </th>
					"""+content+"""
				</table>
			</div>
			</div>
			<div class="col-md-3">

					"""+my+ friend+"""
			</div>
		</div>
	 </div>
	</body>
	</html>
	"""
def workIndex(arr):
	sorted(arr)
	content=""
	for i in range(0,min(10,len(arr))):
		article=arr[i]
		content=content+"<tr><td><a href='/article/"+article[1]+".html'>"+article[4]+"</td><td>"+str(article[0])+"</td></tr>\n"
	write("index.html",index(content).replace('<li><a href="/">','<li class="active"><a href="/">'))
